package handle

import (
	"AcsGo/internal/domain"
	"AcsGo/internal/model"
	"fmt"
)

func HandleReaderCheckDuplicate(str string) (string, error) {
	var sfzh string
	var ok string
	var rdbm string
	var xk string
	var ac string
	readerCheckDuplicate, err := domain.HandleReaderCheckDuplicate(str)
	if err != nil {
		return "", err
	}
	lg.Debugf("HandleReaderCheckDuplicate init: %v", readerCheckDuplicate)

	db, err := model.ConnectDB()
	if err != nil {
		lg.Errorf("HandleReaderCheckDuplicate conndb: %v", err)
		return "", err
	}
	// var reader *model.Reader
	if readerCheckDuplicate.IdCardNo.Value != "" {
		sfzh = readerCheckDuplicate.IdCardNo.Value
		reader, err := model.GetReaderBySfzh(db, sfzh)
		if err != nil {
			ok = "1"
			rdbm = ""
			xk = "1"
			ac = "0"
			queryResponse := domain.InitReaderCheckDuplicateResponseResponse(rdbm, sfzh, ok, xk, ac)
			sb, _ := queryResponse.StringFormat()
			lg.Debugf("succes sfzh 不存在: %v", sb)
			return sb, nil
		}
		ok = "1"
		ac = "1"
		sfzh = reader.SFZH
		// rdbm = reader.BM
		xk = "1"
		queryResponse := domain.InitReaderCheckDuplicateResponseResponse(rdbm, sfzh, ok, xk, ac)
		sb, _ := queryResponse.StringFormat()
		lg.Debugf("HandleReaderCheckDuplicate sfzh succes: %v", sb)
		return sb, nil
	}

	if readerCheckDuplicate.PatronIdentifier.Value != "" {
		rdbm = readerCheckDuplicate.PatronIdentifier.Value
		reader, err := model.GetReaderByBm(db, rdbm)
		if err != nil {
			ok = "1"
			sfzh = ""
			xk = "0"
			ac = "0"
			queryResponse := domain.InitReaderCheckDuplicateResponseResponse(rdbm, sfzh, ok, xk, ac)
			sb, _ := queryResponse.StringFormat()
			lg.Debugf("succes rdbm 不存在: %v", sb)
			return sb, nil
		}
		ok = "1"
		ac = "1"
		// sfzh = reader.SFZH
		rdbm = reader.BM
		xk = "0"
		queryResponse := domain.InitReaderCheckDuplicateResponseResponse(rdbm, sfzh, ok, xk, ac)
		sb, _ := queryResponse.StringFormat()
		lg.Debugf("HandleReaderCheckDuplicate rdbm succes: %v", sb)
		return sb, nil
	}
	return "", fmt.Errorf("HandleReaderCheckDuplicate error must has sfzh or rdbm")
}
